/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 * @version 1.0
 */
package shop.controller.manage.weightrecord;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import shop.core.common.bean.JSONResult;
import shop.core.util.KeyValueHelper;
import shop.core.Services;
import shop.core.util.MD5;
import shop.core.util.excel.ExcelUtils;
import shop.services.manage.weightrecord.WeightrecordService;
import shop.services.manage.weightrecord.bean.Weightrecord;
import shop.core.BaseController;
import shop.core.RequestHolder;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**   
 * @类名称：WeightrecordAction      
 * @创建人：wzl
 * @创建时间：2018-04-23 下午19:46:19      
 * @版本号：1.0
 * @描述：     
 */
@Controller
@RequestMapping("/manage/weightrecord/")
public class WeightrecordAction extends BaseController<Weightrecord> {
    private static final Logger logger = LoggerFactory.getLogger(WeightrecordAction.class);
    @Autowired
    private WeightrecordService weightrecordService;
    private static final String page_toList = "/manage/weightrecord/weightrecordList";
    private static final String page_toSandPitCount = "/manage/Analysis/sandpitlist";
    private static final String page_toCartCount = "/manage/Analysis/carDatelist";
    private static final String page_toProductCount = "/manage/Analysis/productlist";
    private static final String page_toSandDetail = "/manage/Analysis/sandDetail";
    private static final String page_toCarDetail = "/manage/Analysis/carDetail";
    private static final String page_toProductDetail = "/manage/Analysis/productDetail";
    public WeightrecordService getService() {
        return weightrecordService;
    }

    private WeightrecordAction(){
        super.page_toList = page_toList;
        super.page_toAdd = null;
        super.page_toEdit = null;
    }

    /**
     * 跳转到采砂场统计分析页面
     *
     * @return
     */
    @RequestMapping("toSandPitCount")
    public String toSandPitCount() {
        return page_toSandPitCount;
    }

    /**
     * 跳转到车辆统计分析页面
     *
     * @return
     */
    @RequestMapping("toCartCount")
    public String toCartCount() {
        return page_toCartCount;
    }

    /**
     * 跳转到品名统计分析页面
     *
     * @return
     */
    @RequestMapping("toProductCount")
    public String toProductCount() {
        return page_toProductCount;
    }

    /**
     * 跳转到沙场统计分析详情页面
     *
     * @return
     */
    @RequestMapping("toSandDetail")
    public String toSandDetail() {
        return page_toSandDetail;
    }

    /**
     * 跳转到车辆统计分析详情页面
     *
     * @return
     */
    @RequestMapping("toCarDetail")
    public String toCarDetail() {
        return page_toCarDetail;
    }


    /**
     * 跳转到品名统计分析详情页面
     *
     * @return
     */
    @RequestMapping("toProductDetail")
    public String toProductDetail() {
        return page_toProductDetail;
    }
    /**
     * Excel文件导出
     */
    @RequestMapping(value = "/excelDownload", method = RequestMethod.GET)
    public void outExcel(HttpServletRequest request, HttpServletResponse response, Weightrecord weightrecord) throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException {
        response.reset();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssms");
        String dateStr = sdf.format(new Date());
        // 指定下载的文件名
        response.setHeader("Content-Disposition", "attachment;filename=" + dateStr + ".xlsx");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        logger.debug("查询数据库开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<Weightrecord> creditInfoList = weightrecordService.selectList(weightrecord);
        logger.debug("查询数据库结束时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<Weightrecord> ems = new ArrayList<>();
        Map<Integer, List<Weightrecord>> maps = new LinkedHashMap<>();
        SXSSFWorkbook book = null;
        ems.add(new Weightrecord("工作站", "sandpit", 0));
        ems.add(new Weightrecord("日期", "createTime", 0));
        ems.add(new Weightrecord("凭证号", "voucherNo", 0));
        ems.add(new Weightrecord("RFID号", "RFID", 0));
        ems.add(new Weightrecord("车牌号", "cartNo", 0));
        ems.add(new Weightrecord("司机", "driver", 0));
        ems.add(new Weightrecord("品名", "productName", 0));
        ems.add(new Weightrecord("毛重", "totalWeight", 0));
        ems.add(new Weightrecord("皮重", "cartWeight", 0));
        ems.add(new Weightrecord("净重", "sandWeight", 0));
        ems.add(new Weightrecord("金额", "money", 0));
        maps.put(0, ems);
        try {
            logger.debug("创建文件开始时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            book = ExcelUtils.createExcelFile(Weightrecord.class, creditInfoList, maps, "流量数据日报表");
            logger.debug("创建文件结束时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (IllegalArgumentException | IllegalAccessException
                | InvocationTargetException | ClassNotFoundException
                | IntrospectionException | ParseException e1) {
            e1.printStackTrace();
        }
        OutputStream output;
        try {
            output = response.getOutputStream();

            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            //刷新此缓冲的输出流，保证数据全部都能写出
            bufferedOutPut.flush();
            book.write(bufferedOutPut);
            bufferedOutPut.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 插入称重记录
     * @param request
     * @param weightrecord
     * @return
     * @throws Exception
     */
    @Override
    public JSONResult insertJson(HttpServletRequest request, Weightrecord weightrecord) throws Exception {
        JSONResult jsonResult=new JSONResult();
        Weightrecord weightrecordInfo=new Weightrecord();
        weightrecordInfo.setSandpit(weightrecord.getSandpit());
        weightrecordInfo.setVoucherNo(weightrecord.getVoucherNo());
        weightrecordInfo=weightrecordService.selectOne(weightrecordInfo);
        if(weightrecordInfo==null){
            weightrecordService.insert(weightrecord);
            weightrecord=weightrecordService.selectOne(weightrecord);
            jsonResult.setData(weightrecord.getVoucherNo());
            jsonResult.setMessage("插入成功！");
            jsonResult.setSuccess(true);
            return jsonResult;
        }else{
            jsonResult.setMessage("该条记录已存在，请勿重复添加！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }
}
